<?php

namespace App\Kuafu\Order\Service;


use App\Kuafu\CouponExt\Enum\CouponExtEnum;
use App\Kuafu\CouponExt\Model\OrderCouponExtSplitModel;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Enum\OrderInfoEnum;
use App\Kuafu\Order\Exceptions\OrderException;
use Illuminate\Support\Facades\Log;

/**
 * 抖音订单
 */
class OrderDyService extends OrderBaseSplitService
{
    /**
     * 生成订单
     *
     * @param array $data
     * @return OrderHandleService
     * @throws OrderException
     */
    public function genOrder(array $data): OrderHandleService
    {
        $order = new OrderHandleService($this->brandId, $this->shopId);

        $data['sourceType'] = CodeEnum::SOURCE_TYPE_DY_MINI;
        $postData           = OrderService::getOrderFormatPostData($data);
        $order->setDyUserId($data['unionId']);
        $order->dyAppletCalcPrice($postData);
        // TODO 校验金额是否相同

        // 校验三方 ID 是否存在
        $thirdOrderInfo = $order->getOrderInfoByThirdOrderId($data['thirdOrderId']);

        if (!empty($thirdOrderInfo)) {
            $order->switchDyOrderId($data['thirdOrderId']);
            return $order;
        }

        $orderPrice = $order->getOrderPrice();

        if ($orderPrice['orderTotalShouldPrice'] > 0) {
            return $order;
        }
        $order->handleOrder($postData);
        // 更新三方 ID
        $order->updateThirdOrderInfo([
            'order' => [
                'thirdOrderId'     => $data['thirdOrderId'],
                'thirdOrderSource' => $data['thirdOrderSource'],
            ]
        ]);

        foreach ($order->getOrderCalc()->getNeedCheckExtCoupon() as $coupon) {
            $couponType = $coupon['type'] ?? OrderInfoEnum::POS_ORDER_PAYMENT_COUPON_MEITUAN;
            $couponExt  = new OrderCouponExternalService(0, $this->shopId, $this->brandId,
                $order->getOrderId(true));
            $couponExt->resetCouponExtPlatformByPosPayment($couponType);
            $couponExt->consumeCouponExtDouyinApplet($coupon['code'], $coupon['num'],
                (int)$coupon['couponDiscountPrice']);
        }

        return $order;
    }

    /**
     * 更新订单三方信息
     *
     * @return void
     * @throws OrderException
     */
    public function updateThirdOrderInfo(array $data)
    {
        $order = new OrderHandleService($this->brandId, $this->shopId, $this->orderId);
        $order->updateThirdOrderInfo([
            'order' => [
                'thirdOrderId'     => $data['thirdOrderId'],
                'thirdOrderSource' => $data['thirdOrderSource'],
            ]
        ]);

        return;
    }

    /**
     * 批量更新优惠券
     *
     * @param array $data
     * @return void
     */
    public function updateDyOrderCoupon(array $data)
    {
        $order = new OrderHandleService($this->brandId, $this->shopId);
        $order->switchDyOrderId($data['order_info']['order_id']);

        // 获取现在的三方优惠券
        $orderExtCouponList = $order->getOrderExtCoupon(true);
        $orderExtCouponList = collect($orderExtCouponList)
            ->where('extPlatform', CouponExtEnum::EXT_PLATFORM_DOUYIN)
            ->where('couponExtSid', '')
            ->where('couponExtCode', '')
            ->where('couponExtCodeData', '')
            ->toArray();


        // 判断是否存在
        if ($data['coupon_verify_results'][0]['result_code'] != 0) {
            Log::channel('order')->error('抖音核销工具有人重复核销', [
                'data' => $data
            ]);
            // 获取订单情况

            $order = new OrderPayService($this->brandId, $this->shopId, $order->getOrderId(true));

            $order->cancel(true);

            // 修改原来的订单优惠券状态
            foreach ($orderExtCouponList as &$couponExtCoupon) {
                $couponExtCoupon['couponExtStatus'] = CouponExtEnum::COUPON_STATUS_CANCEL;
                $couponExtCoupon['createdAt']       = time();
                $couponExtCoupon['updatedAt']       = time();
            }

            // 批量更新
            foreach ($orderExtCouponList as $item) {
                OrderCouponExtSplitModel::suffix($this->shopId)->where('id', $item['id'])->update($item);
            }

            return;
        }


        // 获取现在优惠券信息
        $couponVerifyResults = $data['coupon_verify_results'];


        // 合并数据
        $couponExtCodeData = [
            'verify_results' => [],
            'error_code'     => 0,
            'description'    => 'kf_callback_success',
            'canUseProduct'  => ''
        ];

        foreach ($orderExtCouponList as $key => $value) {
            $targetCoupon                          = $couponVerifyResults[$key];
            $couponExtCodeData['verify_results'][] = [
                'certificate_id' => $targetCoupon['certificate_id'],
                'verify_id'      => $targetCoupon['verify_id']
            ];

        }

        foreach ($orderExtCouponList as $key => &$couponExtCoupon) {
            $targetCoupon                         = $couponVerifyResults[$key];
            $couponExtCoupon['couponExtCode']     = $targetCoupon['verify_id'];
            $couponExtCoupon['couponExtCodeData'] = json_encode($couponExtCodeData);
            $couponExtCoupon['couponExtStatus']   = CouponExtEnum::COUPON_STATUS_USED;
            $couponExtCoupon['createdAt']         = time();
            $couponExtCoupon['updatedAt']         = time();
        }

        // 批量更新
        foreach ($orderExtCouponList as $item) {
            OrderCouponExtSplitModel::suffix($this->shopId)->where('id', $item['id'])->update($item);
        }
    }

}
